package com.platform.user.service;

import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.WriterException;
import com.platform.bean.JsonResult;
import com.platform.user.dao.ItemApplyDao;
import com.platform.user.dao.ItemClaimNoticeDao;
import com.platform.user.dao.LostHelpNoticeDao;
import com.platform.user.entity.ItemApply;
import com.platform.user.entity.ItemClaimNotice;
import com.platform.user.entity.LostHelpNotice;
import com.platform.user.entity.User;
import com.platform.utils.BaiduSimilarImageServerUtils;
import com.platform.utils.Base64Utils;
import com.platform.utils.QrCodeUtils;
import com.platform.utils.UploadFileToRemoteUtils;
import org.apache.ibatis.javassist.NotFoundException;
import org.json.JSONException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Service
public class ItemQRCodeService {

    @Resource
    private LostHelpNoticeDao lostHelpNoticeDao;
    @Resource
    private ItemClaimNoticeDao itemClaimNoticeDao;
    @Resource
    private ItemApplyDao itemApplyDao;

    public int parsingQRCode(Map<String, Object> params, User user) throws ChecksumException, NotFoundException, com.google.zxing.NotFoundException, IOException, FormatException, JSONException {
        String imageBase64 = params.get("imageBase64").toString();
        String msg = QrCodeUtils.decodeFromBase64(imageBase64);
        Integer itemSort = Integer.parseInt(msg.split("\\+")[0]);
        Integer itemId = Integer.parseInt(msg.split("\\+")[1]);

        if (itemSort == 0) {
            LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(itemId);

            // 查询是否申请了
            HashMap<String, Object> req = new HashMap<>();
            req.put("itemSort", itemSort);
            req.put("itemId", itemId);
            req.put("applicantUserId", user.getId());
            req.put("applyStatus", 0);
            ItemApply itemApply = itemApplyDao.queryOneByParams(req);
            if (itemApply == null) {
                return 0;
            }

            lostHelpNotice.setReturnerUserId(user.getId());
            lostHelpNotice.setItemStatus(3);
            String imageUrlToBase64 = Base64Utils.convertImageUrlToBase64(lostHelpNotice.getImageCover());
            Map<String, Object> baiduImageReq = new HashMap<>();
            baiduImageReq.put("brief", lostHelpNotice.getId());
            baiduImageReq.put("classId1", "2");
            baiduImageReq.put("image", imageUrlToBase64);
            int i = BaiduSimilarImageServerUtils.updateImage(baiduImageReq);
            if (i == -1) {
                System.out.println("百度云更新失败");
                return -1;
            }
            lostHelpNoticeDao.update(lostHelpNotice);
        } else {
            ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(itemId);

            // 查询是否申请了
            HashMap<String, Object> req = new HashMap<>();
            req.put("itemSort", itemSort);
            req.put("itemId", itemId);
            req.put("applicantUserId", user.getId());
            req.put("applyStatus", 0);
            ItemApply itemApply = itemApplyDao.queryOneByParams(req);
            if (itemApply == null) {
                return 0;
            }

            itemClaimNotice.setClaimantUserId(user.getId());
            itemClaimNotice.setItemStatus(3);
            String imageUrlToBase64 = Base64Utils.convertImageUrlToBase64(itemClaimNotice.getImageCover());
            Map<String, Object> baiduImageReq = new HashMap<>();
            baiduImageReq.put("brief", itemClaimNotice.getId());
            baiduImageReq.put("classId1", "5");
            baiduImageReq.put("image", imageUrlToBase64);
            int i = BaiduSimilarImageServerUtils.updateImage(baiduImageReq);
            if (i == -1) {
                System.out.println("百度云更新失败");
                return -1;
            }
            itemClaimNoticeDao.update(itemClaimNotice);
        }
        return 1;
    }

    public String generateQRCode(String msg) {
        //String msg = "190";
        int width = 200;
        int height = 200;

        try {
            String base64Image = QrCodeUtils.generateQRCodeBase64(msg, width, height);
//            System.out.println("Base64 QR Code: " + base64Image);
            return processBase64ToUrl("data:image/png;base64," + base64Image);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 根据url删除图片
     *
     * @param url 图片url
     */
    private void deleteImageByUrl(String url) {
        if (url != null) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(url,
                    "/opt/docker/apache/www/images/lost_and_found");
        }
    }

    /**
     * 将base64封面图片转换为url
     *
     * @param imageBase64 base64图片
     * @return 图片url
     * @throws IOException 异常
     */
    private String processBase64ToUrl(String imageBase64) throws IOException {
        StringBuilder fileName = new StringBuilder();
        Map<String, String> imageTypeAndCode = Base64Utils.splitImageTypeAndCode(imageBase64);
        String imageType = null;
        String base64Data = null;

        if (imageTypeAndCode != null) {
            imageType = imageTypeAndCode.get("imageType");
            base64Data = imageTypeAndCode.get("base64Data");
        }

        fileName.append(System.currentTimeMillis()).append(".").append(imageType);
        // Base64转文件
        MultipartFile multipartFile = Base64Utils.convertBase64ToMultipart(base64Data, fileName.toString());
        JsonResult jsonResult = UploadFileToRemoteUtils.uploadFileToRemoteServer(multipartFile, "/opt/docker/apache/www/images/lost_and_found");
        return (String) jsonResult.getData();
    }
}
